/**
 * 
 */
package org.mspring.mlog.web.module.admin;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.mspring.mlog.common.Keys;
import org.mspring.mlog.core.ServiceFactory;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.service.security.UserService;
import org.mspring.mlog.support.log.Log;
import org.mspring.mlog.utils.AvatarUtils;
import org.mspring.mlog.utils.UploadUtils;
import org.mspring.mlog.web.security.SecurityUtils;
import org.mspring.platform.utils.CookieUtils;
import org.mspring.platform.utils.ImageUtils;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.ResponseEntity;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Gao Youbo
 * @since 2012-8-7
 * @Description
 * @TODO
 */
@Widget
@RequestMapping("/admin/self")
public class Admin_SelfInfoWidget extends Admin_AbstractWidget {
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/info")
    public String viewUserInfo(@ModelAttribute User user, HttpServletRequest request, HttpServletResponse response, Model model) {
        user = SecurityUtils.getCurrentUser(request);
        model.addAttribute("user", user);
        return "/admin/self/info";
    }

    @RequestMapping("/info/save")
    @Log
    public String edit_save(@ModelAttribute User user, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (StringUtils.isNotBlank(user.getPassword())) { // 如果密码框不为空，那么修改密码
            String password = StringUtils.getMD5(user.getPassword());

            user.setPassword(password);
            userService.update(user);
            // 重置用户登录信息
            request.getSession().invalidate();
            CookieUtils.setCookie(response, Keys.IS_REMEMBER_USER_COOKIE, "false", 365);
        } else {
            String password = SecurityUtils.getCurrentUser(request).getPassword();
            user.setPassword(password);
            userService.merge(user);
            user = userService.getUserByName(user.getName());
            request.getSession().setAttribute(Keys.CURRENT_USER, user);
        }
        return "redirect:/admin/self/info";
    }

    /**
     * 图像
     * 
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/avatar")
    public String avatar(HttpServletRequest request, HttpServletResponse response, Model model) {
        User currentUser = SecurityUtils.getCurrentUser(request);
        if (currentUser != null) {
            model.addAttribute("currentUser", currentUser);
        }
        return "/admin/self/avatar";
    }

    /**
     * 上传头像
     * 
     * @return
     */
    @RequestMapping("/avatar/upload")
    @ResponseBody
    public ResponseEntity avatar_save(@RequestParam("avatar") MultipartFile avatar, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResponseEntity rsp = new ResponseEntity();
        // 限定上传图片的格式
        boolean isImage = ImageUtils.isImage(FilenameUtils.getExtension(avatar.getOriginalFilename()));
        if (!isImage) {
            rsp.setSuccess(false);
            rsp.setMessage("上传文件格式不正确");
            return rsp;
        }
        // 限定上传图片大小
        long size = avatar.getSize() / 1024;
        if (size > 512) {
            rsp.setSuccess(false);
            rsp.setMessage("上传图片大不能超过512K");
            return rsp;
        }

        User currentUser = SecurityUtils.getCurrentUser(request);
        String url = AvatarUtils.uploadAvatar(avatar, currentUser.getId());
        if (url == null) {
            rsp.setSuccess(false);
            rsp.setMessage("头像上传失败");
        } else {
            rsp.setSuccess(true);
            rsp.put("url", UploadUtils.UPLOAD_FOLDER + url);
        }
        return rsp;
    }

    /**
     * 剪裁并保存头像
     * 
     * @return
     */
    @RequestMapping("/avatar/save")
    public String avatar_save(HttpServletRequest request, HttpServletResponse response, Model model) {
        Integer x1 = new Integer(request.getParameter("x1"));
        Integer y1 = new Integer(request.getParameter("y1"));
        Integer x2 = new Integer(request.getParameter("x2"));
        Integer y2 = new Integer(request.getParameter("y2"));
        String filePath = request.getParameter("file");

        User currentUser = SecurityUtils.getCurrentUser(request);

        File file = UploadUtils.getAbsoluteUploadFile(filePath);

        try {
            // 剪裁图片
            BufferedImage image = AvatarUtils.cropAvatar(file, currentUser.getId(), x1, y1, x2, y2);
            // 保存图像
            String large = AvatarUtils.buildLargeAvatar(image, currentUser.getId());
            String small = AvatarUtils.buildSmallAvatar(image, currentUser.getId());

            // 删除头像所使用的零时文件
            ServiceFactory.getFileService().deleteFile(filePath);

            // 更新用户信息
            User user = userService.get(currentUser.getId());
            user.setLargeAvatar(large);
            user.setSmallAvatar(small);
            userService.update(user);
            return prompt(model, "", "头像保存成功", "/admin/self/avatar");
        } catch (IOException e) {
            // TODO: handle exception
            return prompt(model, "头像修改失败");
        }
    }
}
